﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};

Axis.Admin.SliderList = {
    Init: function () {
        var thisObj = this;
        thisObj.Grid.Init();

        thisObj.EventClick();
        var cmaskdate = new CMaskDate();
        cmaskdate.Init($("input[role=datepicker]"));
        $("button").button();
    },
    Grid: {
        ParentID: 23,
        ID: "#GridContents",
        PagesID: "#GridPages",
        GridURL: '../Slider/Service/SliderGrid.ashx',
        postData: { Action: "GET",Context:'Admin' },
        Init: function () {
            var thisObj = this;
            var options = {
                url: thisObj.GridURL,
                mtype: 'POST',
                postData: thisObj.postData,
                datatype: "json",
                colNames: [
                    'ID', 'Code', 'Tên', 'ProjectID', 'Dự án', 'Url', 'Ảnh', 'Mô tả', 'Vị trí','','Trạng Thái', 'Xử lý'
                ],
                colModel: [
                    { name: 'ID', index: 'ID', width: 50, hidden: true, frozen: true },
                    { name: 'Code', index: 'Code', width: 100, frozen: true, hidden: true },
                    { name: 'Name', index: 'Name', width: 150, frozen: true, hidden: true },
                    { name: 'ProjectID', index: 'ProjectID', width: 100, hidden: true },
                    { name: 'ProjectName', index: 'ProjectName', width: 200 },
                    { name: 'Url', index: 'Url', width: 200 },
                    { name: 'Image', index: 'Image', width: 100, align: 'center' },
                    { name: 'Description', index: 'Description', width: 250, hidden: true },
                    { name: 'ZOrder', index: 'ZOrder', width: 50,align: 'center' },
                    { name: 'Status', index: 'ZOrder', width: 1,align: 'center', hidden: true },
                    { name: 'StatusString', index: 'ZOrder', width: 100,align: 'center' },
                     
                    { name: 'Action', index: 'Action', width: 90, align: 'center' }
                ],
                afterInsertRow: function (rowid, aData, addData) {
                 var action = $.string.Format("<img class='imgAction' src='../../Images/16x16/edit.png' onclick=\"ShowEdit('{0}')\"/><img class='imgAction' src='../../Images/16x16/cancel.png' onclick=\"DeleteNews('{0}')\"/>", rowid);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'Action', action);
                    var iconStatus='s_enable.png';
                    if(aData.Status=='-1')
                     iconStatus='s_delete.png';
                      if(aData.Status=='1')
                     iconStatus='s_visible.png';
                     var StatusString= $.string.Format("<img class='imgAction' src='../../Images/16x16/{0}' onclick=\"ActionStatus('{1}',{2})\"/>", iconStatus,rowid,aData.Status);
                     $(thisObj.ID).jqGrid('setCell', rowid, 'StatusString', StatusString );
                },
                gridComplete: function () {
                    $('.imgSliderImage').tooltip({
                        delay: 0,
                        track: true,
                        showURL: false,
                        bodyHandler: function () {
                            return $("<img/>").attr("src", this.src);
                        }
                    });
                },
                onCellSelect: function (rowid, iCol, cellcontent, e) {

                },
                onSelectRow: function (rowid, status, e) {

                },
                ondblClickRow: function (rowid, iRow, iCol, e) {

                },
                subGrid: true,
                subGridRowExpanded: function (subgrid_id, row_id) {
                    var subgrid_table_id, pager_id;
                    subgrid_table_id = subgrid_id + "_t";
                    pager_id = "p_" + subgrid_table_id;
                    var rowData = $(thisObj.ID).jqGrid('getRowData', row_id);
                    $("#" + subgrid_id).html(rowData.Description);
                },
                multiselect: true,
                height: 'auto',
                rownumbers: true,
                autowidth: true,
                //forceFit: true,
                shrinkToFit: false,
                rowNum: 10,
                pager: thisObj.PagesID
            };
            thisObj.GridObj = new CGrid(options);
            thisObj.GridObj.Init(thisObj.ID);
            thisObj.GridObj.NavGrid();
        },
        Reload: function () {
            var thisObj = this;
            if (thisObj.GridObj)
                thisObj.GridObj.ReloadGrid();
        },
        SelectRow: function () {
            var thisObj = this;
            if (thisObj.GridObj) {
                return thisObj.GridObj.SelectRow();
            }
            return null;
        }
    },
    DialogEdit: {
        ID: "#FormEdit",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            thisObj.ClearForm();

            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Edit User",
                    width: 500,
                    open: function () {
                        if (CKEDITOR.instances["txtDescription"]) {


                        }
                        else {
                            var config = {
                                width: 480,
                                height: 200,
                                toolbar: [
                                    ['Source', '-', 'Bold', 'Italic', 'Underline']
                                ]
                            };
                            CKEDITOR.replace("txtDescription", config);
                        }
                    }
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "";
            switch (action) {
                case "INSERT":
                    thisObj.Dialog.SetTitle("Add Banner");
                    $(thisObj.ID).find("[data-role='INSERT']").show();
                    $(thisObj.ID).find("#txtLoginName").focus();
                     $("#txtStatus").attr('checked', 'checked');
                    buttonText = "Add";
                    break;
                case "UPDATE":
                    thisObj.Dialog.SetTitle("Edit: " + opts.Name);
                    $.each(opts, function (key, value) {
                        if (key == "Image") {
                            value = $(value).attr("FileName") || "";
                        }
                        if (key == "Description") {
                            if (CKEDITOR && CKEDITOR.instances["txtDescription"])
                                CKEDITOR.instances["txtDescription"].setData(value);
                        }
                        $(thisObj.ID).find("[data-field=" + key + "]").val(value);
                        if (key == "ProjectID" && value) {
                            $("#cboLinkBy").val("Project").trigger("change");
                        }
                        if (key =='Status'){
                                $("#txtStatus").attr('checked', 'checked');
                                if (value != "0")
                                  $("#txtStatus").removeAttr('checked');
                                    }
                    });
                    buttonText = "Update";
                    break;
            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.SliderList.Update(action, opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        ClearForm: function () {
            $("#FormEdit").find("[data-field]").each(function () {
                var $this = $(this);
                $this.val("");
                if ($this.is("select")) {
                    var value = $this.find("option:eq(0)").attr("value");
                    $this.val(value);
                }
            });
            $("#FormEdit").find("[data-role='INSERT']").hide();
            if (CKEDITOR && CKEDITOR.instances["txtDescription"])
                CKEDITOR.instances["txtDescription"].setData("");
        }
    },
    Update: function (type, opts) {
        var thisObj = this;
        var data = {};
        switch (type) {
            case "INSERT":
            case "UPDATE":
                $("#FormEdit").find("[data-field]").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field")) {
                        var key = $this.attr("data-field");
                        var value = $this.val() || "";
                        if ($this.attr('type') == 'checkbox') {
                            if ($this.is(':checked'))
                                value = 0;
                            else
                                value = 1;
                        }
                        data[key] = value;
                    }
                });
                break;
            case "DELETE":
                data.ID = opts.ID;
                break;
            case "ACTIVE":
            case "DEACTIVE":
               // data = opts;
               // type="UPDATE";
                break;
        }

        data.Action = type;
        if (CKEDITOR && CKEDITOR.instances["txtDescription"])
            data.Description = CKEDITOR.instances["txtDescription"].getData();
            if (typeof USER_ID != "undefined") {
            data.UserID = USER_ID;
            data.SecrectToken = SECRECT_TOKEN;
        }
        $.Ajax({
            url: '../Slider/Service/SliderAction.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    if (data.IsSuccessfull) {
                        thisObj.Grid.Reload();
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    DialogFilter: {
        Init: function () { }
    },
    EventClick: function () {
        var thisObj = this;
        $("#imgUserAdd").click(function () {
            thisObj.DialogEdit.Init("INSERT");
        });
        $("#imgUserEdit").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID)
                thisObj.DialogEdit.Init("UPDATE", rowData);
            else alert("Please Select Row");
        });
        $("#imgUserDel").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Xóa",
                    Content: $.string.Format("Bạn có chắc muốn xóa: [{0}].", rowData.Name)
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update("DELETE", rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa",
                    Content: "Vui lòng chọn nội dung cần xóa.",
                });
            }

        });
        $("#imgUserFilter").click(function () {
            thisObj.DialogFilter.Init();
        });
        $("#btnSelectImg").click(function () {
            var finder = new CKFinder();
            finder.resourceType = 'Images';
            finder.startupPath = "Images:/Slider/";
            finder.selectActionFunction = function (fileUrl) {
                $('#txtImage').val(fileUrl);
            };
            finder.popup();
        });
    }
};
$(function () {
    Axis.Admin.SliderList.Init();

});
function ShowEdit(rowID) {
    var thisObj = Axis.Admin.SliderList;
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.ID)
        thisObj.DialogEdit.Init("UPDATE", rowData);
}

function ActionStatus(rowID,Status){
return;
var thisObj=Axis.Admin.SliderList;
    var newStatus="Active";
    var action="DEACTIVE";
    Status=parseInt(Status);
    if(Status==1){
    newStatus="DeActive";
    action="ACTIVE";
    }
    if(Status==-1)
    return;
    var rowData={ID:rowID};
    if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Cập nhật trang thái Banner Top",
                    Content: $.string.Format("Bạn có chắc muốn thay đôi trạng thái banner top", newStatus)
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update(action, rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa Banner",
                    Content: "Vui lòng chọn Banner cần xóa."
                });
            }


}